/**
 *<p>Copyright: Copyright (c) 2012</p> 
 *<p>Company: SCPII</p>
 *<p>Project:scpii-api</p>
 *@author xiezhouyan
 *@Date 2013-4-8 下午3:35:33
 *@version 1.0
 *@description:
 */
package com.scpii.api.controller.auto;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.scpii.api.domain.auto.UserCars;
import com.scpii.api.service.auto.UserCarsService;
import com.scpii.api.util.FileUtil;
import com.scpii.api.util.PrincipalUtil;

@Controller
@RequestMapping("/auto/userCars")
public class UserCarsController {

	@Resource
	private UserCarsService userCarsService;

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/maintenance", method = RequestMethod.GET)
	@ResponseBody
	public List<UserCars> getMaintenance() {
		return userCarsService.getMaintenanceByUserId(PrincipalUtil
				.getPrincipal().getId());
	}

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Boolean addUserCars(
			@RequestParam(value = "photo", required = false) MultipartFile photo,
			@Valid UserCars userCars) {
		UserCars persistUserCars = userCarsService
				.selectByPrimaryKey(StringUtils.upperCase(userCars
						.getLicenceId()));
		if (persistUserCars != null) {
			return false;
		}
		userCars.setUserId(PrincipalUtil.getPrincipal().getId());
		userCars.setCreateBy(PrincipalUtil.getPrincipal().getId());
		userCars.setThumbImage(FileUtil.save(photo).getThumbImage());
		userCars.setAppId(PrincipalUtil.getPrincipal().getAppId());
		userCars.setCreateDt(new Date());
		userCars.setLicenceId(StringUtils.upperCase(userCars.getLicenceId()));
		userCarsService.insertSelective(userCars);
		return true;
	}
}
